import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_demo/core/common/net/code.dart';
import 'package:flutter_demo/core/common/utils/file_utils.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:get/get.dart' as GET;
import 'package:path_provider/path_provider.dart';

class DownloadManager {
  //static String uri = "http://10.12.1.28:8613";
  static String uri = "http://192.168.1.102:8613";
  static String subPath = "download";

  static Future<String?> downloadFile(String fileName) async {
    // 获取存储路径

    Directory? savedDir = await FileUtils.findPath(subPath);
    if (savedDir == null) return null;
    Dio dio = Dio();
    //设置连接超时时间
    dio.options.connectTimeout = 5000;
    //设置数据接收超时时间
    dio.options.receiveTimeout = 5000;
    Response response;
    String path = "${savedDir.path}/$fileName";
    try {
      String url = "$uri/$fileName";
      logger.i("下载url:$url");
      response = await dio.download(url, path);
    } on DioError catch (e) {
      int code = 500;
      if (e.type == DioErrorType.connectTimeout ||
          e.type == DioErrorType.receiveTimeout) {
        code = Code.NETWORK_TIMEOUT;
      }
      Code.errorHandleFunction(code, "下载出错", false);
      return null;
    }
    if (response.statusCode == 200) {
      if (await FileUtils.fileExists(subPath, fileName)) {
        logger.i(path);
        GET.Get.snackbar(
          "下载",
          "下载完成",
        );
      }
      return path;
    }
    return null;
  }
}
